package com.example.study.common;

import com.example.study.service.UserReader;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author by CLP
 * @Classname BeanConfig
 * @Description
 * @Date 2020/9/8 15:28
 */
@Component
public class BeanConfig implements InitializingBean, ApplicationContextAware {
    private Map<String, UserReader> queryServiceImplMap = new HashMap<>();
    private ApplicationContext applicationContext;

    public UserReader createQueryService(String type) {

        UserReader userReader = queryServiceImplMap.get(type);
        if (userReader == null) {
            return queryServiceImplMap.get("UserReader1Impl");
        }
        return userReader;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, UserReader> beanMap = applicationContext.getBeansOfType(UserReader.class);
        //遍历该接口的所有实现，将其放入map中
        for (UserReader serviceImpl : beanMap.values()) {
            queryServiceImplMap.put(serviceImpl.getClass().getSimpleName(), serviceImpl);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
